package com.per.mybootall.test;

import com.alibaba.fastjson.JSON;
import io.swagger.models.auth.In;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.apache.poi.ss.formula.functions.T;

import java.util.*;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicReferenceArray;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2022-03-29
 * Time: 13:34:16
 * Description:构造树形结构【Bean类型】
 */
public class test17 {

    public static void main(String[] args) {
        List<Bean> initList=init();
        Map<Integer,Bean> tempMap=new HashMap();
        List<Bean> tree=new ArrayList<>();

        for(Bean bean:initList){
            tempMap.put(bean.getId(),bean);
            Integer pid=bean.getPid();
            if(tempMap.containsKey(pid)){
                Bean pBean=tempMap.get(pid);
                if(pBean.getChild()==null){
                    pBean.setChild(new ArrayList<>());
                }
                pBean.getChild().add(bean);
            }
            if(bean.getPid()==0){
                tree.add(bean);
            }
        }
        System.out.println(JSON.toJSONString(tree));
    }

    public static class Bean{
        private Integer id;
        private Integer pid;
        private List<Bean> child;

        public Integer getId() {
            return id;
        }

        public Bean(Integer id, Integer pid) {
            this.id = id;
            this.pid = pid;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getPid() {
            return pid;
        }

        public void setPid(Integer pid) {
            this.pid = pid;
        }

        public List<Bean> getChild() {
            return child;
        }

        public void setChild(List<Bean> child) {
            this.child = child;
        }
    }
    public static List<Bean> init(){
        List finalList=new ArrayList(){{
            add(new Bean(1,0));
            add(new Bean(2,0));
            add(new Bean(3,0));
            add(new Bean(4,2));
            add(new Bean(5,1));
            add(new Bean(6,4));

        }};
       return finalList;
    }
}
